package com.study.zookeeperAPI;

import org.apache.zookeeper.*;
import org.apache.zookeeper.data.Stat;

import java.io.IOException;
import java.util.concurrent.CountDownLatch;

public class GetData implements Watcher {

    private static ZooKeeper zooKeeper = null;
    private static Stat stat = new Stat();
    private static CountDownLatch latch = new CountDownLatch(1);

    private static String connectStr = "127.0.0.1:2181,127.0.0.1:2182,127.0.0.1:2184";
    private static int sessionTime = 5000;

    public static void main(String[] args) throws InterruptedException {
        zooKeeper = connectZk();
//        getDataSync();

        //getDataASync();

        String path2 = "/mytest";
        ZooKeeper zk2 = connectZkWithAuth();
        try{
            zk2.create(path2, "".getBytes(), ZooDefs.Ids.CREATOR_ALL_ACL, CreateMode.EPHEMERAL);
            //zooKeeper.addAuthInfo("digest", "foo:true".getBytes());
            zooKeeper.getData(path2, false,stat);
            zooKeeper.delete(path2, -1);
            System.out.println("成功删除节点！=====" + path2);
        }catch (Exception e){
            System.out.println("e is =" + e.getMessage());
        }




        /*Stat stat1 = exitsNodeSync(path);
        System.out.println(stat1);
        stat1 = exitsNodeSync(path2);
        if(exitsNodeSync(path2) == null){
            try {
                zooKeeper.create(path2, "testVal".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
                zooKeeper.setData(path2, "mytest1".getBytes(), -1);
                zooKeeper.delete(path,-1);
            }catch (KeeperException e){
                System.out.println("KeeperException ====" + e);
            }
        }

        System.out.println(stat1);*/
        //Thread.sleep(Integer.MAX_VALUE);

    }


    private static String path = "/zk-book";


    private static String authPath = "/zk-book-auth-test";

    public static ZooKeeper connectZkWithAuth(){

        ZooKeeper zk = null;
        try{
            zk = new ZooKeeper(connectStr, sessionTime, new GetData());
            //设置权限
            zk.addAuthInfo("digest", "foo:true".getBytes());
        }catch (IOException e){
            System.out.println("IOException is ====" + e.getMessage());
        }
        return zk;
    }

    public static void getDataASync() {
        try {
            zooKeeper.getData(path, true, new IDataCallback(), null);
            zooKeeper.setData(path, "1234567890".getBytes(), -1);
        } catch (KeeperException e) {

            System.out.println("KeeperException is e" + e.getMessage());
        } catch (InterruptedException e) {
            System.out.println("InterruptedException is e");
        }
    }

    /**
     * 同步获取data
     */
    public static void getDataSync(){
        try{
            byte [] res = zooKeeper.getData(path, true, stat);
            System.out.println("res====" + new String(res));
            System.out.println(stat.getCzxid() + "," + stat.getMzxid() + "," + stat.getVersion());
            zooKeeper.setData(path, "hello6".getBytes(), -1);
            System.out.println(new String(zooKeeper.getData(path, true, stat)));
            Thread.sleep(Integer.MAX_VALUE);
        }catch (KeeperException e){
            System.out.println("KeeperException is====" + e.getMessage());
        }catch (InterruptedException e){
            System.out.println("InterruptedException is====" + e.getMessage());
        }

    }


    /**
     * 连接zk
     * @return
     */
    public static ZooKeeper connectZk(){

        try{
            zooKeeper = new ZooKeeper(connectStr, sessionTime, new GetData());
            latch.await();
        }catch (IOException e){
            System.out.println("IOException ====" + e);
        }catch (InterruptedException e){
            System.out.println("InterruptedException =====" + e);
        }
        return zooKeeper;
    }

    public void process(WatchedEvent watchedEvent) {
        if(Event.KeeperState.SyncConnected.equals(watchedEvent.getState())){
            System.out.println("connect success！！！！");
            if(Event.EventType.None == watchedEvent.getType() && null == watchedEvent.getPath()){
                latch.countDown();
            }
            else if (Event.EventType.NodeDataChanged.equals(watchedEvent.getType())){
                try{
                    zooKeeper.getData(watchedEvent.getPath(), true,new IDataCallback(),null);
                    System.out.println("node datachange============");
                }catch (Exception e){
                    System.out.println("e=====" + e.getMessage());
                }

            }else  if(Event.EventType.NodeCreated == watchedEvent.getType()){
                System.out.println("Node("+ watchedEvent.getPath() + ")Created");
                exitsNodeSync(watchedEvent.getPath());
            }else if(Event.EventType.NodeDeleted == watchedEvent.getType()){
                System.out.println("Node("+ watchedEvent.getPath() + ")Delete");
                exitsNodeSync(watchedEvent.getPath());
            }
        }
    }

    public static Stat exitsNodeSync(String path){
        Stat stat = null;
        try{
            stat = zooKeeper.exists(path, true);
        }catch (InterruptedException e){
            System.out.println("InterruptedException is" + e.getMessage());
        }catch (KeeperException e){
            System.out.println("KeeperException is " + e.getMessage());
        }
        return stat;
    }


    static class IDataCallback implements AsyncCallback.DataCallback{
        public void processResult(int rc, String path, Object ctx, byte[] data, Stat stat) {
            System.out.println("return code is " + rc + ", path is " + path + ", data is" + new String(data));
            System.out.println("czxid is" + stat.getCzxid() + ", mzxid: " + stat.getMzxid() + "version: " + stat.getVersion());
        }
    }
}
